package com.castile.secondkill.validator;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 校验器
 *
 * @author Hongliang Zhu
 * @create 2023-03-05 21:39
 */
@Component
public class ValidatorImpl implements InitializingBean {

    private Validator validator;

    /**
     * 校验器
     *
     * @param bean 要校验的对象
     * @return 校验结果
     */
    public ValidationResult validate(Object bean) {

        Set<ConstraintViolation<Object>> constraintViolations =
                this.validator.validate(bean);

        ValidationResult validationResult = new ValidationResult();

        if (!constraintViolations.isEmpty()) {
            validationResult.setHasError(true);
            constraintViolations.forEach(constraintViolation -> {
                String propertyPath = constraintViolation.getPropertyPath().toString();
                String message = constraintViolation.getMessage();
                validationResult.getErrorMsgMap().put(propertyPath, message);
            });

        }

        return validationResult;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 将hibernate validator 通过工厂的初始化方式使其实例化
        this.validator = Validation.buildDefaultValidatorFactory().getValidator();
    }
}
